package com.mms.data;

import com.mms.pojo.FanBlog;
import com.mms.pojo.FanDict;
import com.mms.service.FanBlogService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by dan3652@sina.com on 2016-12-27 11:01.
 */
public class Get51ctoData {
    public static void getList(String ticketurl, FanBlogService service,FanDict dict) throws Exception {
        String url = ticketurl;
        Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36").get();
        Elements elements = document.select(".rightbox > .r_li");
        FanBlog blog = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Element element : elements){
            blog = new FanBlog();
            Elements title = element.select("h4 a");
            String titleName = title.text();
            String link = title.attr("href").trim();
            String content = element.select(".r_li_cont p").text().replace("更多>>","");
            String date = element.select(".r_li_cont02 p span").first().text();
            date = date.substring(3,date.length());
//            System.out.print(titleName+"---"+link+"---"+content+"---"+date+"\n");
            blog = (FanBlog) service.find("from FanBlog a where a.title=?",new Object[]{titleName}).get(0);
            if(blog == null){
                blog.setTitle(titleName);
                blog.setUrl(link);
                blog.setAddtime(simpleDateFormat.parse(date));
                blog.setContent(content);
                blog.setDict(dict);
                service.save(blog);
            }else {
            }
        }
    }

    public static String setUTF8(String endcoding, String str) throws UnsupportedEncodingException {
        return new String(str.getBytes(endcoding), "UTF-8");
    }
}
